package com.hkyp.ss.course.provider.impl;

import com.hkyp.ss.course.apis.UURelationService;
import com.hkyp.ss.course.apis.dto.common.PageReq;
import com.hkyp.ss.course.apis.dto.common.PageResp;
import com.hkyp.ss.course.apis.dto.response.SimpleUserVO;
import com.hkyp.ss.course.apis.exception.DaoException;
import com.hkyp.ss.course.apis.exception.UnacceptableException;
import com.hkyp.ss.course.apis.utils.BeanMapper;
import com.hkyp.ss.course.provider.model.User;
import com.hkyp.ss.course.provider.model.mediate.UURelation;
import com.hkyp.ss.course.provider.repository.UserRepository;
import com.hkyp.ss.course.provider.repository.mediate.UURelationRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service(version = "1.0")
@Transactional(rollbackFor = Exception.class)
public class UURelationServiceImpl implements UURelationService {

    @Autowired
    UURelationRepository uuRelationRepository;

    @Autowired
    UserRepository userRepository;



    // 获取该用户关注的人
    @Override
    @Transactional(readOnly = true)
    public PageResp<SimpleUserVO> selectByFromId(PageReq pageReq, Long userId) {

        return selectByFromIdOrToId(pageReq,userId,0);
    }

    // 获取该用户的粉丝
    @Override
    @Transactional(readOnly = true)
    public PageResp<SimpleUserVO> selectByToId(PageReq pageReq, Long userId) {


        UURelation uuRelation = new UURelation();

        uuRelation.setToId(userId);

        Example<UURelation> uuRelationExample = Example.of(uuRelation);
        pageReq.setSortfield(null);
        //先对userIds分页查询，然后在去用户表查具体用户
        Page<UURelation> uuRelationPage = uuRelationRepository.findAll(uuRelationExample, pageReq.toPageable());

        List<UURelation> uuRelationList = uuRelationPage.getContent();

        //获取我粉丝的用户id集合
        Set<Long> userIdsSet = uuRelationList.stream().map(UURelation::getFromId).collect(Collectors.toSet());

////////////////////////////////////////////////////////////////////////
        List<UURelation> uuRelations = uuRelationRepository.findAllByToIdInAndFromIdEquals(userIdsSet, userId);
        Set<Long> mutualIds = uuRelations.stream().map(UURelation::getToId).collect(Collectors.toSet());

////////////////////////////////////////////////////////////////////////
        List<User> users = userRepository.findAllById(userIdsSet);

        List<SimpleUserVO> simpleUserVOS = BeanMapper.mapList(users, SimpleUserVO.class);
        simpleUserVOS.forEach(simpleUserVO -> {
            if(mutualIds.contains(simpleUserVO.getId())){
                simpleUserVO.setFollowed(1);
            }else {
                simpleUserVO.setFollowed(0);
            }
        });

        log.info("即将发给前端的数据："+simpleUserVOS);

        return new PageResp<>(uuRelationPage,simpleUserVOS);
    }

    @Override
    public void putUURelation(Long userId, Long toUserId,Integer action) {
        if(toUserId == null|| action == null){
            throw new UnacceptableException("toUserId或action没有传入");
        }
        if(Objects.equals(userId,toUserId)){
            throw new UnacceptableException("您不可以关注自己");
        }

        UURelation uuRelation = uuRelationRepository.findByFromIdAndToId(userId, toUserId);
        User toUser = userRepository.findById(toUserId).orElseThrow(()->new UnacceptableException("此id的用户不存在"));
        // 1表示执行关注
        if(action == 1){
            if(uuRelation!=null){
                throw new UnacceptableException("您已关注过该用户");
            }
            UURelation uuRelation1 = new UURelation();
            uuRelation1.setFromId(userId);
            uuRelation1.setToId(toUserId);
            uuRelation1.setCreateAt(System.currentTimeMillis());
            uuRelationRepository.save(uuRelation1);

            toUser.setFansNum(toUser.getFansNum()+1);
            userRepository.save(toUser);
        }else if(action == 0){
            if(uuRelation == null){
                return;
            }
            uuRelationRepository.deleteById(uuRelation.getId());
            toUser.setFansNum(toUser.getFansNum()-1);
            userRepository.save(toUser);

        }else {
            throw new UnacceptableException("action参数非法");
        }

    }


    // action=0:fromId; action=1:toId
    public PageResp<SimpleUserVO> selectByFromIdOrToId(PageReq pageReq, Long userId, Integer action) {

        UURelation uuRelation = new UURelation();

        if(action == 0){
            uuRelation.setFromId(userId);
        }else if(action == 1){
            uuRelation.setToId(userId);
        }else {
            throw new DaoException("输入参数有误(程序内部)");
        }


        Example<UURelation> uuRelationExample = Example.of(uuRelation);
        pageReq.setSortfield(null);
        //先对userIds分页查询，然后在去用户表查具体用户
        Page<UURelation> uuRelationPage = uuRelationRepository.findAll(uuRelationExample, pageReq.toPageable());

        List<UURelation> uuRelationList = uuRelationPage.getContent();

        Set<Long> userIdsSet;
        if(action == 0){
            userIdsSet = uuRelationList.stream().map(UURelation::getToId).collect(Collectors.toSet());
        }else{
            userIdsSet = uuRelationList.stream().map(UURelation::getFromId).collect(Collectors.toSet());
        }

        List<User> users = userRepository.findAllById(userIdsSet);

        List<SimpleUserVO> simpleUserVOS = BeanMapper.mapList(users, SimpleUserVO.class);
        log.info("即将发给前端的数据："+simpleUserVOS);

        return new PageResp<>(uuRelationPage,simpleUserVOS);
    }



}
